package com.hyq.market.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

/**
 * Created by LS on 2017/6/5 0005.
 * SharedPreferences工具类
 */

public class SPUtils {
    private static final String SP_NAME = "ebike";
    private static SharedPreferences sp;

    private static synchronized SharedPreferences getSp() {
        if(sp == null) {
           // sp = BaseApplication.getAppContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }

        return sp;
    }

    public static void putString(String key, String value) {
        getSp().edit().putString(key, value).apply();
    }

    public static void putFloat(String key, float value) {
        getSp().edit().putFloat(key, value).apply();
    }

    public static void getFloat(String key, float value) {
        getSp().getFloat(key, value);
    }

    public static String getString(String key) {
        return getSp().getString(key, "");
    }

    public static String getString(String key, String def) {
        return getSp().getString(key, def);
    }

    public static void putBoolean(String key, boolean value) {
        getSp().edit().putBoolean(key, value).apply();
    }

    public static boolean getBoolean(String key, boolean def) {
        return getSp().getBoolean(key, def);
    }

    public static void put(String key, String value) {
        getSp().edit().putString(key, value).apply();
    }

    public static boolean saveObject(Object object){
        SharedPreferences.Editor edit = getSp().edit();
        Gson gson=new Gson();
        String json=gson.toJson(object);
        return edit.putString(object.getClass().getName(), json).commit();
    }

    public static <T> T getObject(Class<T> t){
        String json= getSp().getString(t.getName(),"");
        Gson gson=new Gson();
        T t1=json==null?null:gson.fromJson(json,t);
        return t1;
    }

    public static <T> void removeObject(Context context,Class<T> t){
        SharedPreferences.Editor edit = getSp().edit();
        edit.remove(t.getName()).commit();
    }
}
